package com.own.business.wechat.base.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.own.business.wechat.base.constant.ConstantWechat;
import com.own.business.wechat.base.em.WechatCodeEnum;
import com.own.business.wechat.base.exception.WechatBaseException;

/**
 * WechatCodeUtil
 *
 * @author chenxueli
 * @date 2023-06-30 10:25:26
 */
public final class WechatCodeUtil {

    private static final String KEY = "errcode";

    /**
     * 获取错误码内容
     *
     * @param object 转json对象的响应
     * @return 错误码内容
     */
    public static WechatCodeEnum check(JSONObject object) {
        if (object.containsKey(KEY)) {
            var code = object.getString(KEY);
            return check(code);
        }
        return WechatCodeEnum.SUCCESS;
    }

    /**
     * 获取错误码内容
     *
     * @param code code
     * @return 错误码内容
     */
    public static WechatCodeEnum check(String code) {
        return ConstantWechat.CODE_MAP.getOrDefault(code, WechatCodeEnum.NOT_FOUND);
    }

    /**
     * 获取错误码内容
     *
     * @param code code
     * @return 错误码内容
     */
    public static WechatCodeEnum check(Integer code) {
        return check(String.valueOf(code));
    }

    /**
     * 验证是否成功
     *
     * @param object 转json对象的响应
     */
    public static void checkThrow(JSONObject object) {
        if (!object.containsKey(KEY)) {
            return;
        }
        var code = object.getString(KEY);
        var em = check(code);
        if (!em.success()) {
            throw new WechatBaseException(em);
        }
    }

    /**
     * 解析响应
     *
     * @param body 响应字符串
     * @return 解析后的对象
     */
    public static JSONObject resolve(String body) {
        var object = JSON.parseObject(body);
        checkThrow(object);
        return object;
    }

}
